import 'package:bigegg/entity/im/xmm_im_talk.dart';
import 'package:bigegg/global/routes/xmm_routes.dart';
import 'package:bigegg/utils/xmm_date_utils.dart';
import 'package:bigegg/utils/xmm_string_utils.dart';
import 'package:bigegg/widget/image/xmm_circle_cached_network_image.dart';
import 'package:bigegg/widget/xmm_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:get/get.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';

import 'xmm_conversation_controller.dart';

class XmmConversationPage extends StatefulWidget {
  const XmmConversationPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return XmmConversationPageState();
  }
}

class XmmConversationPageState extends State<XmmConversationPage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  @override
  bool get wantKeepAlive => true;

  XmmConversationController controller = Get.find<XmmConversationController>();

  @override
  void initState() {
    super.initState();
    controller.getConversationList();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Obx(
          () =>
      controller.talkList.isNotEmpty ? ListView.builder(
        padding: EdgeInsets.only(bottom: 100.w),
        itemCount: controller.talkList.length,
        itemBuilder: (context, index) {
          var item = controller.talkList.elementAt(index);
          return buildItem(item);
        },
      ): getEmptyWidget(),
    );
  }

  Widget buildItem(XmmImTalk item) {
    return GestureDetector(
      onTap: () => Get.toNamed(XmmRoutes.chatPage, arguments: item.user.userId),
      child: Slidable(
        endActionPane: ActionPane(
          motion: const ScrollMotion(),
          extentRatio: 0.19,
          children: [
            CustomSlidableAction(
              onPressed: (context) => controller.deleteConversation(item.user.userId ?? ""),
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
              child: Image.asset(
                'assets/images/xmm_icon_delete_talk.png',
                width: 34.w,
                height: 32.w,
              ),
            )
          ],
        ),
        child: Container(
          padding: EdgeInsets.only(left: 18.w, right: 20.w),
          height: 76.w,
          child: Row(
            children: [
              SizedBox(
                height: 46.w,
                width: 50.w,
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    Align(
                      alignment: Alignment.bottomLeft,
                      child: XmmCircleCachedNetworkImage(
                        imageUrl: item.user.getAvatarUrl ?? "",
                        width: 44.w,
                        height: 44.w,
                      ),
                    ),
                    Align(
                      alignment: Alignment.topRight,
                      child: getUnreadNumWidget(item),
                    )
                  ],
                ),
              ),
              SizedBox(width: 6.w),
              Expanded(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      XmmStringUtils.truncateText(item.user.nickname ?? "", 15),
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: const Color(0xFF202020),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    SizedBox(height: 10.w),
                    Text(
                      getMessageContent(item.conversation.lastMessage),
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: const Color(0x4D000000),
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    )
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 18.w),
                alignment: Alignment.topRight,
                child: Text(
                  getTime(item.conversation.lastMessage?.receivedTime ?? 0),
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: const Color(0x4D000000),
                  ),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  String getMessageContent(RCIMIWMessage? message) {
    if (message is RCIMIWTextMessage) {
      return XmmStringUtils.truncateText(message.text ?? '', 12);
    } else if (message is RCIMIWImageMessage) {
      return '[ImageMessage]';
    } else if (message is RCIMIWVoiceMessage) {
      return '[VoiceMessage]';
    } else if (message is RCIMIWFileMessage) {
      return '[FileMessage]';
    } else if (message is RCIMIWMediaMessage) {
      return '[MediaMessage]';
    } else if (message is RCIMIWRecallNotificationMessage) {
      return '[RecallNotificationMessage]';
    } else if (message is RCIMIWLocationMessage) {
      return '[LocationMessage]';
    }
    return 'Unknown';
  }

  String getTime(int time) {
    if (time > 0) {
      return XmmDateUtils.parseTime(DateTime.fromMillisecondsSinceEpoch(time));
    }
    return '';
  }

  Widget getUnreadNumWidget(XmmImTalk item) {
    if (item.conversation.unreadCount == 0) {
      return Container();
    }
    String num = (item.conversation.unreadCount ?? 0) > 99
        ? '99+'
        : item.conversation.unreadCount.toString();
    return Container(
      padding: EdgeInsets.only(left: 4.w, right: 4.w),
      decoration: BoxDecoration(
        color: Colors.red,
        border: Border.all(color: Colors.white, width: 1.w),
        borderRadius: BorderRadius.circular(17),
      ),
      child: Text(
        num,
        style: TextStyle(
          fontSize: 10.sp,
          color: Colors.white,
        ),
      ),
    );
  }
}
